﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using WpfApplication1.Properties;
using Dimeng.ArdisPostProcessor.HomagLC4Adsn;
using Dimeng.ArdisPostProcessor.HomagLC4.Ardis;
using System.IO;
using Dimeng.ArdisPostProcessor.HomagLC4;
using System.Windows;
using SpreadsheetGear;
using Microsoft.Win32;
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    public class MainViewModel : ViewModelBase
    {
        R41Data r41Data;
        private string r41;
        public MainViewModel(string r41path)
        {
            r41 = r41path;
            path = Settings.Default.Path;
            TrimValue = Settings.Default.TrimValue;
            ExportPath = Settings.Default.ExportPath;
            IsExportExcel = false;
            AnalysisLevel = Settings.Default.AnalysisLevel;

            StartCommand = new RelayCommand(this.start);
            SaveCommand = new RelayCommand(this.saveSettings);
            ExportListCommand = new RelayCommand(this.exportList);
            ExportR41Command = new RelayCommand(this.exportR41, this.canExportR41);
        }

        private bool canExportR41()
        {
            return true;
        }

        private void exportList()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = ".xlsx|*.xlsx";
            if (saveFileDialog.ShowDialog() == true)
            {
                var r2 = this.bootstrap.GetResult2();
                var book = Factory.GetWorkbook();
                var cell = book.Worksheets[0].Cells;

                cell[0, 0].Value = "材料";
                cell[0, 1].Value = "长度";
                cell[0, 2].Value = "宽度";

                int counter = 0;
                foreach (var item in this.Patterns.Where(it => it.IsChosen))
                {
                    cell[counter + 1, 0].Value = "SN" + item.Comment;
                    cell[counter + 1, 1].Value = item.Material;
                    cell[counter + 1, 2].Value = item.Length;
                    cell[counter + 1, 3].Value = item.Width;
                    counter++;
                }

                book.SaveAs(saveFileDialog.FileName, FileFormat.OpenXMLWorkbook);
                MessageBox.Show("成功导出");
            }
        }

        private void exportR41()
        {
            string copName = r41Data.R41Name.ToUpper().Replace(".R41", "") + "_first";
            if (!Directory.Exists(ExportPath))
                Directory.CreateDirectory(ExportPath);
            var creator = new R41Creator(bootstrap);
            creator.CreateCop(ExportPath, copName);
        }

        private void saveSettings()
        {
            Settings.Default.Path = path;
            Settings.Default.TrimValue = this.TrimValue;
            Settings.Default.ExportPath = this.ExportPath;
            Settings.Default.AnalysisLevel = this.AnalysisLevel;
            Settings.Default.Save();
            ExpressionDictionary.Save();
        }

        public void Loaddata()
        {
            try
            {
                //原始的r41数据
                r41Data = R41Helper.AnalysisR41(this.r41);

                //准备文件夹
                string folder1 = System.IO.Path.Combine(this.path, r41Data.R41Name, "初次切割");
                string folder2 = System.IO.Path.Combine(this.path, r41Data.R41Name, "二次切割");
                if (!Directory.Exists(folder1))
                {
                    Directory.CreateDirectory(folder1);
                }
                if (!Directory.Exists(folder2))
                {
                    Directory.CreateDirectory(folder2);
                }

                //分析和拆分
                bootstrap = new Bootstrap(r41Data, Settings.Default.TrimValue, Settings.Default.AnalysisLevel, Settings.Default.LimitCutWidth);
                bootstrap.Start();

                //把第一结果，生成lc4
                var r1 = bootstrap.GetResult1();
                R41Helper.GetPatternTrimsAndMaterials(r1);
                r1.Parts.ForEach(it => it.PartQtyDone = it.PartQty);
                R41Helper.AnalysisFullCuts(r1);

                //if (IsExportImages)
                //{
                //    for (int i = 0; i < r1.Patterns.Count; i++)
                //    {
                //        var pa = r1.Patterns[i];
                //        var file = System.IO.Path.Combine(folder1, $"{i + 1}.png");
                //        DrawingHelper.Draw(file, r1.FullCuts.Where(it => it.CutPatternNo == pa.PatternNumber).ToList(), pa);
                //    }
                //}
                //if (IsExportExcel)
                //{
                //    DataExporter.ExportXLSX(r1, System.IO.Path.Combine(folder1, $"export.xls"));
                //}
                //using (FileStream fs = new FileStream(System.IO.Path.Combine(folder1, r1.R41Name + ".lc4"), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
                //{
                //    LC4Writer writer = new LC4Writer(fs, r1);
                //    writer.Write();
                //    fs.Close();
                //}


                //把第二结果生成lc4
                var r2 = bootstrap.GetResult2();
                R41Helper.GetPatternTrimsAndMaterials(r2);
                r2.Parts.ForEach(it => it.PartQtyDone = it.PartQty);
                R41Helper.AnalysisFullCuts(r2);

                //if (IsExportImages)
                //{
                for (int i = 0; i < r2.Patterns.Count; i++)
                {
                    var pa = r2.Patterns[i];
                    var file = System.IO.Path.Combine(folder2, $"{bootstrap.Result2Comments[i]}.png");
                    DrawingHelper.Draw(file, r2.FullCuts.Where(it => it.CutPatternNo == pa.PatternNumber).ToList(), pa);

                    PatternViewModel pvm = new PatternViewModel(pa.PatternW, pa.PatternL, pa.PatternMaterial, bootstrap.Result2Comments[i], file,
                        r2.FullCuts.Where(it => it.CutPatternNo == pa.PatternNumber).ToList());
                    this.Patterns.Add(pvm);
                }

                this.SelectedPattern = this.Patterns[0];

                r2.R41Name = r41Data.R41Name.ToUpper().Replace(".R41", "") + "_second";
                using (FileStream fs = new FileStream(System.IO.Path.Combine(folder2, r2.R41Name + ".lc4"), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
                {
                    LC4Writer writer = new LC4Writer(fs, r2);
                    writer.Write();
                    fs.Close();
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message + Environment.NewLine + error.StackTrace);
            }
        }

        private void start()
        {

        }

        private string path;
        public string Path
        {
            get { return path; }
            set
            {
                path = value;
                base.RaisePropertyChanged("Path");
            }
        }

        public string MachineName
        {
            get { return Settings.Default.MachineName; }
            set
            {
                Settings.Default.MachineName = value;
                base.RaisePropertyChanged("MachineName");
            }
        }

        public double BookHeight
        {
            get { return Settings.Default.BookHeight; }
            set
            {
                Settings.Default.BookHeight = value;
                base.RaisePropertyChanged("BookHeight");
            }
        }

        public double BladeThick
        {
            get { return Settings.Default.BladeThick; }
            set
            {
                Settings.Default.BladeThick = value;
                base.RaisePropertyChanged("BladeThick");
            }
        }

        public int MaxLevel
        {
            get { return Settings.Default.MaxLevel; }
            set
            {
                Settings.Default.MaxLevel = value;
                base.RaisePropertyChanged("MaxLevel");
            }
        }

        public double LimitCutWidth
        {
            get { return Settings.Default.LimitCutWidth; }
            set
            {
                Settings.Default.LimitCutWidth = value;
                base.RaisePropertyChanged("LimitCutWidth");
            }
        }

        public double NormalLength
        {
            get { return Settings.Default.NormalLength; }
            set
            {
                Settings.Default.NormalLength = value;
                base.RaisePropertyChanged("NormalLength");
            }
        }

        public double NormalWidth
        {
            get { return Settings.Default.NormalWidth; }
            set
            {
                Settings.Default.NormalWidth = value;
                base.RaisePropertyChanged("NormalWidth");
            }
        }

        public bool IsExportExcel { get; set; }

        public double TrimValue { get; set; }

        public string ExportPath { get; set; }

        public int AnalysisLevel { get; set; }

        private ObservableCollection<PatternViewModel> patterns = new ObservableCollection<PatternViewModel>();
        public ObservableCollection<PatternViewModel> Patterns
        {
            get { return patterns; }
            set
            {
                patterns = value;
                base.RaisePropertyChanged("Patterns");
            }
        }

        public PatternViewModel selectedPattern = null;
        public PatternViewModel SelectedPattern
        {
            get { return selectedPattern; }
            set
            {
                selectedPattern = value;
                base.RaisePropertyChanged("SelectedPattern");
            }
        }

        public RelayCommand StartCommand { get; private set; }
        public RelayCommand SaveCommand { get; private set; }
        public RelayCommand ExportListCommand { get; private set; }
        public RelayCommand ExportR41Command { get; private set; }
        Bootstrap bootstrap;
    }
}
